package cn.dyp.com.manualcontrol.request;


import org.json.JSONException;
import org.json.JSONObject;

import cn.dyp.com.manualcontrol.bean.ControllerStatus;

/**
 * 获取控制器状态的请求类
 * 
 * @author asus
 *
 */
public class GetControllerStatusRequest extends AgricultureRequest {
	// action name
	private static final String ACTION = "getContorllerStatus";
	// 存放控制器状态
	private ControllerStatus mControllerStatus;

	/**
	 * 获取存放存放控制器状态的ControllerStatus
	 * 
	 * @return ControllerStatus
	 */
	public ControllerStatus getControllerStatus() {
		return mControllerStatus;
	}

	/**
	 * 设置存放存放控制器状态的ControllerStatus
	 * 
	 * @param controllerStatus
	 *            存放控制器状态的类
	 */
	public void setControllerStatus(ControllerStatus controllerStatus) {
		this.mControllerStatus = controllerStatus;
	}

	/**
	 * 设置Action
	 * 
	 * @see cn.dyp.com.manualcontrol.request.BaseRequest#getActionName()
	 */
	@Override
	protected String getActionName() {
		return ACTION;
	}

	public GetControllerStatusRequest(String userName) {
		super(userName);
	}

	/**
	 * jason协议时的获取body函数
	 * 
	 * @see cn.dyp.com.manualcontrol.request.BaseRequest#onGetJasonBody()
	 */
	@Override
	protected String onGetJasonBody() {
		JSONObject jsonObj = new JSONObject();
		try {
			jsonObj.put("username", userName);
			return jsonObj.toString();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * jason协议时解析回应函数
	 * 
	 * @see cn.dyp.com.manualcontrol.request.AgricultureRequest#onJasonParese(String)
	 */
	@Override
	protected void onJasonParese(String responseStr) {
		try {
			JSONObject jsonRespObj = new JSONObject(responseStr);
			if (jsonRespObj != null && mControllerStatus != null) {
				if (jsonRespObj.has("result")) {
					String result = jsonRespObj.getString("result");
					// 判断请求是否成功
					if (result.equals("ok")) {
						isSuccess = true;
					} else {
						isSuccess = false;
					}
				}
				// 蜂鸣器控制器
				if (jsonRespObj.has("Buzzer")) {
					mControllerStatus.setBuzzer(jsonRespObj.getInt("Buzzer"));
				}
				// 水泵控制器
				if (jsonRespObj.has("WaterPump")) {
					mControllerStatus.setWaterPump(jsonRespObj
							.getInt("WaterPump"));
				}
				// 路灯控制器
				if (jsonRespObj.has("Roadlamp")) {
					mControllerStatus.setRoadLamp(jsonRespObj
							.getInt("Roadlamp"));
				}
				// 风扇控制器
				if (jsonRespObj.has("Blower")) {
					mControllerStatus.setBlower(jsonRespObj.getInt("Blower"));
				}
			} else {
				isSuccess = false;
			}
		} catch (JSONException e) {
			isSuccess = false;
			e.printStackTrace();
		}
	}

}
